// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import easing = cc.easing;

const {ccclass, property} = cc._decorator;

export enum petPosition {
    pet1 = 0,
    pet2 = 1,
    pet3 = 2,
    pet4 = 3,
    pet5 = 4,
    pet6 = 5,
    pet7 = 6,
    pet8 = 7
}

@ccclass
export default class petMediator extends cc.Component {

    @property({type : cc.Enum(petPosition),displayName : "宠物位置"})
    curPetPosition : petPosition = petPosition.pet1;

    @property(cc.Node)
    roleNode : cc.Node = null;

    onLoad(){
        cc.game.on("petDie",()=>{
            let spk = this.node.getChildByName("spine").getComponent(sp.Skeleton);
            spk.setAnimation(0,"liulei",true);
        })
    }

    protected onDestroy(): void {
        cc.game.off("petDie");
    }

    update (dt) {
        let pos;
        if(this.curPetPosition == petPosition.pet1){
            pos = this.roleNode.getChildByName("petNode1").convertToWorldSpaceAR(cc.v2(0,0));
        } else if(this.curPetPosition == petPosition.pet2){
            pos = this.roleNode.getChildByName("petNode2").convertToWorldSpaceAR(cc.v2(0,0));
        } else if(this.curPetPosition == petPosition.pet3){
            pos = this.roleNode.getChildByName("petNode3").convertToWorldSpaceAR(cc.v2(0,0));
        } else if(this.curPetPosition == petPosition.pet4){
            pos = this.roleNode.getChildByName("petNode4").convertToWorldSpaceAR(cc.v2(0,0));
        } else if(this.curPetPosition == petPosition.pet5){
            pos = this.roleNode.getChildByName("petNode5").convertToWorldSpaceAR(cc.v2(0,0));
        }else if(this.curPetPosition == petPosition.pet6){
            pos = this.roleNode.getChildByName("petNode6").convertToWorldSpaceAR(cc.v2(0,0));
        }else if(this.curPetPosition == petPosition.pet7){
            pos = this.roleNode.getChildByName("petNode7").convertToWorldSpaceAR(cc.v2(0,0));
        }else{
            // if(this.roleNode.getChildByName("petNode8")){
            //     pos = this.roleNode.getChildByName("petNode8").convertToWorldSpaceAR(cc.v2(0,0));
            // }
            if(this.roleNode.getChildByName("petNode3")){
                pos = this.roleNode.getChildByName("petNode8").convertToWorldSpaceAR(cc.v2(0,0));
            }
        }
        let pos2 = cc.find("Canvas").convertToNodeSpaceAR(pos);
        let myPos = cc.v2(this.node.x,this.node.y);
        let pos3 = pos2.sub(myPos).normalize();
        let distance = pos2.sub(myPos).mag();
        if(distance > 20){
            this.node.x += pos3.x * 3 * distance / 60;
            this.node.y += pos3.y * 3 * distance / 60;
        }
    }
}
